/**
 *
 */
package com.da.lon.wang.xlg.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.activity.NewPartyActivity;
import com.da.lon.wang.xlg.activity.PartyInfoActivity;
import com.da.lon.wang.xlg.activity.ProductsActivity;
import com.da.lon.wang.xlg.activity.ResultSearchActivity;
import com.da.lon.wang.xlg.activity.StoreListActivity;
import com.da.lon.wang.xlg.activity.WebViewActivity;
import com.da.lon.wang.xlg.bean.AutoLoginBean;
import com.da.lon.wang.xlg.bean.ResultSearchBean.ResultSearchListBean.SearchResultOther;
import com.da.lon.wang.xlg.bean.ResultSearchBean.ResultSearchListBean.SearchResultOther.SearchResultOtherItems;
import com.da.lon.wang.xlg.bean.SerializableMap;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;

import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;

/**
 * 辅助工具类
 *
 * @author hongming.wang
 * @创建时间： 2015年11月24日 上午11:46:50
 * @项目名称： AMapLocationDemo2.x
 * @文件名称: Utils.java
 * @类型名称: Utils
 */
public class Utils {
    /**
     * 开始定位
     */
    public final static int MSG_LOCATION_START = 0;
    /**
     * 定位完成
     */
    public final static int MSG_LOCATION_FINISH = 1;
    /**
     * 停止定位
     */
    public final static int MSG_LOCATION_STOP = 2;

    public final static String KEY_URL = "URL";
    public final static String URL_H5LOCATION = "file:///android_asset/location.html";

    /**
     * 根据定位结果返回定位信息的字符串
     *
     * @param loc
     * @return
     */
    // public synchronized static String getLocationStr(AMapLocation location) {
    // if (null == location) {
    // return null;
    // }
    // StringBuffer sb = new StringBuffer();
    // try {
    // // errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
    // if (location.getErrorCode() == 0) {
    // sb.append("定位成功" + "\n");
    // sb.append("定位类型: " + location.getLocationType() + "\n");
    // sb.append("经    度    : " + location.getLongitude() + "\n");
    // sb.append("纬    度    : " + location.getLatitude() + "\n");
    // sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
    // sb.append("提供者    : " + location.getProvider() + "\n");
    //
    // if (location.getProvider().equalsIgnoreCase(
    // android.location.LocationManager.GPS_PROVIDER)) {
    // // 以下信息只有提供者是GPS时才会有
    // sb.append("速    度    : " + location.getSpeed() + "米/秒"
    // + "\n");
    // sb.append("角    度    : " + location.getBearing() + "\n");
    // // 获取当前提供定位服务的卫星个数
    // sb.append("星    数    : " + location.getSatellites() + "\n");
    // } else {
    // // 提供者是GPS时是没有以下信息的
    // sb.append("国    家    : " + location.getCountry() + "\n");
    // sb.append("省            : " + location.getProvince() + "\n");
    // sb.append("市            : " + location.getCity() + "\n");
    // sb.append("城市编码 : " + location.getCityCode() + "\n");
    // sb.append("区            : " + location.getDistrict() + "\n");
    // sb.append("区域 码   : " + location.getAdCode() + "\n");
    // sb.append("地    址    : " + location.getAddress() + "\n");
    // sb.append("兴趣点    : " + location.getPoiName() + "\n");
    // }
    // } else {
    // // 定位失败
    // sb.append("定位失败" + "\n");
    // sb.append("错误码:" + location.getErrorCode() + "\n");
    // sb.append("错误信息:" + location.getErrorInfo() + "\n");
    // sb.append("错误描述:" + location.getLocationDetail() + "\n");
    // }
    // } catch (Exception e) {
    // // TODO: handle exception
    // }
    // return sb.toString();
    // }

    /**
     * 从assert文件夹中读取省市区的json文件，然后转化为json对象
     */
    public static JSONObject initJsonData(Context context) {
        JSONObject mJsonObj = null;
        try {
            StringBuffer sb = new StringBuffer();
            InputStream is = context.getAssets().open("location.json");
            int len = -1;
            byte[] buf = new byte[1024];
            while ((len = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, len, "utf-8"));
            }
            is.close();
            mJsonObj = new JSONObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mJsonObj;
    }

    /**
     * 清空筛选条件
     */
    public static void clearFilter(String search_sattr) {
        try {
            PreferenceUtils.getInstance().SetSettingString(
                    PreferencesConfig.SEARCH_SATTR, search_sattr);
            /**
             * 设置筛选分类CID 为 空
             */
            PreferenceUtils.getInstance().SetSettingString(
                    PreferencesConfig.CID, "");
            MyApplication.getInstance().setPrice_hight("");
            MyApplication.getInstance().setPrice_small("");
            if (MyApplication.getInstance().getCategorylist() != null) {
                for (int i = 0; i < MyApplication.getInstance()
                        .getCategorylist().size(); i++) {
                    MyApplication.getInstance().getCategorylist().get(i)
                            .setSelect(false);
                }
            }
            if (MyApplication.getInstance().getOtherlist() != null) {
                for (int i = 0; i < MyApplication.getInstance().getOtherlist()
                        .size(); i++) {
                    SearchResultOther searchResultOther = MyApplication
                            .getInstance().getOtherlist().get(i);
                    ArrayList<SearchResultOtherItems> items = searchResultOther
                            .getItems();
                    for (int j = 0; j < items.size(); j++) {
                        MyApplication.getInstance().getOtherlist().get(i)
                                .getItems().get(j).setSelect(false);
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 开启定位
     *
     * @param
     * @return
     */

    public static void startLocationClientAddress(Context context,
                                                  Handler mHandler) {
        try {
            AMapLocationClient locationClient = new AMapLocationClient(
                    context.getApplicationContext());
            AMapLocationClientOption locationOption = new AMapLocationClientOption();
            // 设置定位模式为高精度模式
            locationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
            // 设置定位监听
            locationClient.setLocationListener((AMapLocationListener) context);
            initOption(locationOption);
            // 设置定位参数
            locationClient.setLocationOption(locationOption);
            // 启动定位
            locationClient.startLocation();
            mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    // 根据控件的选择，重新设置定位参数
    private static void initOption(AMapLocationClientOption locationOption) {
        // 设置是否需要显示地址信息
        if (locationOption != null) {
            locationOption.setNeedAddress(true);
            // 是否允许模拟位置！
            locationOption.setMockEnable(true);
            locationOption.setOnceLocation(true);
            /**
             * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
             * 注意：只有在高精度模式下的单次定位有效，其他方式无效
             */
            locationOption.setGpsFirst(false);
            // String strInterval = etInterval.getText().toString();
            // if (!TextUtils.isEmpty(strInterval)) {
            // // 设置发送定位请求的时间间隔,最小值为1000，如果小于1000，按照1000算
            // locationOption.setInterval(Long.valueOf(strInterval));
            // }
        }

    }

    /**
     * 清除webview 的cookie
     *
     * @param context
     */
    public static void clearCookies(Context context) {
        @SuppressWarnings("unused")
        CookieSyncManager cookieSyncMngr = CookieSyncManager
                .createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }

    /**
     * 更改馆之后更新用户信息
     */
    public static void updateUserInfo(final Context context) {
        try {
            HttpLoader<AutoLoginBean> httpLoader = new HttpLoader<AutoLoginBean>(
                    context, XLGConstants.URL + "Login-memberinfo",
                    AutoLoginBean.class);
            AjaxParams params = new AjaxParams();
            params.put(
                    "user_id",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.USER_ID, ""));
            params.put("token", XLGDataUtils.encrypt2MD5("Login" + "2015#$%"
                    + "memberinfo"));
            params.put("device_type", "1");
            httpLoader
                    .setManagerListener(new OnWebLoadListener<AutoLoginBean>() {

                        @Override
                        public void OnStart() {

                        }

                        @Override
                        public void OnError(String error) {
                        }

                        @Override
                        public void onSuccess(AutoLoginBean t) {
                            if (t != null && "000000".equals(t.getCode())
                                    && t.getResult() != null) {
                                if (t.getResult().getStore_id() != null) {
                                    PreferenceUtils
                                            .getInstance()
                                            .SetSettingString(
                                                    PreferencesConfig.STORE_ID,
                                                    t.getResult().getStore_id());
                                }
                                if (t.getResult().getStore_name() != null) {
                                    PreferenceUtils
                                            .getInstance()
                                            .SetSettingString(
                                                    PreferencesConfig.STORE_NAME,
                                                    t.getResult()
                                                            .getStore_name());
                                }
                            } else {
                                ToastUtils.showShort(context, t.getMessage());
                            }
                        }
                    });
            httpLoader.loadData(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 首页界面跳到原生界面
     *
     * @param context 上下文
     * @param status  activity_group_id状态 1跳原生界面 2跳网页
     * @param url     网页地址
     */
    public static void onClickBannerStartActivity(Context context, int status,
                                                  String url) {

        if (!MyApplication.isNetworkAvailable(context)) {
            return;
        }
        try {
            Map<String, String> urlRequest = URLRequest(url);
            final SerializableMap myMap = new SerializableMap();
            myMap.setMap(urlRequest);// 将map数据添加到封装的myMap<span></span>中
            if (url.indexOf("/p/") != -1) {
                Intent intent = new Intent(context, ProductsActivity.class);
                String product_number = url.substring(url.indexOf("/p/") + 3,
                        url.indexOf(".html"));
                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.PRODUCT_NUMBER, product_number);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                context.startActivity(intent);
            } else if (url.contains("activity_id=")) {
                String activity_id = "activity_id=";
                String id = url.substring(url.indexOf(activity_id)
                        + activity_id.length());
                Intent intent = new Intent(context, PartyInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("id", id);
                intent.putExtras(bundle);
                context.startActivity(intent);

            } else if (url.contains("activity_group_id=")) {
                if (status == 2) {
                    Intent intent = new Intent(context, WebViewActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("flag", 002);
                    bundle.putString("url", url);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                } else {
                    String activity_group_id = "activity_group_id=";
                    String id = url.substring(url.indexOf(activity_group_id)
                            + activity_group_id.length());
                    Intent intent = new Intent(context, NewPartyActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("id", id);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }
            } else if (url.contains("all-product") && url.contains("cid=")) {
                // String cidString = url.substring(url.indexOf("cid=") + 4);
                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.SEARCH_SATTR, "");
                Intent intent = new Intent(context, ResultSearchActivity.class);
                Bundle bundle1 = new Bundle();
                // bundle1.putString("cid", cidString);
                bundle1.putSerializable("map", myMap);
                intent.putExtras(bundle1);
                context.startActivity(intent);
            } else if (url.contains("all-product") && url.contains("sattr=")) {
                // String sattr = URLDecoder.decode(url.substring(url
                // .indexOf("sattr=") + 6));
                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.SEARCH_SATTR, "");

                Intent intent = new Intent(context, ResultSearchActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("map", myMap);
                intent.putExtras(bundle);
                context.startActivity(intent);
            } else if (url.contains("all-product") && url.contains("orderby")) {
                if (url.contains("?")) {
                    String[] split = url.split("\\?");
                    url = split[0];
                }
                String orderby = url.substring(url.indexOf("orderby-") + 8);
                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.SEARCH_SATTR, "");
                Intent intent = new Intent(context, ResultSearchActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("orderby", orderby);
                bundle.putBoolean("choessxl", true);
                bundle.putSerializable("map", myMap);
                intent.putExtras(bundle);
                context.startActivity(intent);
            } else if (url.contains("Experience-index")) {
                Intent intent = new Intent(context, StoreListActivity.class);
                context.startActivity(intent);
            } else {
                Intent intent = new Intent(context, WebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("flag", 002);
                bundle.putString("url", url);
                intent.putExtras(bundle);
                context.startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // public static void share(Context context, String party_name, String uri)
    // {
    // try {
    // Intent intent11 = new Intent(Intent.ACTION_SEND);
    // intent11.setType("text/plain");
    // intent11.putExtra(Intent.EXTRA_SUBJECT, "分享");
    // if (uri.contains("?")) {
    // uri = uri + "&shop_id=" + MyApplication.getShopId();
    // } else {
    // uri = uri + "?shop_id=" + MyApplication.getShopId();
    // }
    // intent11.putExtra(Intent.EXTRA_TEXT, party_name + "\n" + uri);
    // context.startActivity(Intent.createChooser(intent11, "分享"));
    // } catch (Exception e) {
    // Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT).show();
    // }
    // }

    /**
     * 分享
     *
     * @param context     上下文
     * @param pro_title   分享的活动标题
     * @param pro_content 分享的活动内容
     * @param uri         分享的活动地址
     * @param uri         分享图片地址
     */
    public static void showShare(Context context, final String pro_title,
                                 final String pro_content, String uri, String imagesUrl) {
        if (null == uri || uri.trim().equals("")) {
            return;
        }
        if (uri.contains("?")) {
            uri = uri + "&shop_id=" + MyApplication.getShopId() + "&is_share=1";
        } else if (!uri.contains("?")) {
            uri = uri + "?shop_id=" + MyApplication.getShopId() + "&is_share=1";
        }
        ShareSDK.initSDK(context);
        OnekeyShare oks = new OnekeyShare();
        // 关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
        // oks.setNotification(R.drawable.ic_launcher,
        // getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(pro_content != null && pro_content.length() != 0 ? pro_title
                : "徐州欧咖");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(uri);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(pro_content != null && pro_content.length() != 0 ? pro_content
                : pro_title);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        if (null != imagesUrl && !imagesUrl.trim().equals("")
                && imagesUrl.contains("http")) {
            oks.setImageUrl(imagesUrl);
        } else {
            oks.setImageUrl("http://p19.qhimg.com/bdm/128_128_/t014d6f5cad99eed773.png");
        }
        // 确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(uri);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(pro_content + "\n" + uri);
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(context.getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(uri);

        // 启动分享GUI
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform,
                                cn.sharesdk.framework.Platform.ShareParams paramsToShare) {
                if ("WechatMoments".equals(platform.getName())) {
                    paramsToShare.setTitle(pro_title);
                }
            }
        });
        oks.show(context);
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * Glide加载图片到指定控件，调整图片大小
     *
     * @param context   上下文
     * @param path      图片地址
     * @param file      图片文件
     * @param imageView 图片空间
     * @param width     设定图片宽
     * @param height    设定图片高
     * @param type      设定默认图片的形状 0为长方形默认图片 1为正方形默认图片 2为首页横向广告图
     */
    public static void loadImageByGlide(Context context, String path,
                                        File file, ImageView imageView, int width, int height, int type) {
        if (context != null && imageView != null) {
            if (null != path && !path.trim().equals("") && width == 0
                    && height == 0 && type == 0) {
                Glide.with(context).load(path)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);

            } else if (null != path && !path.trim().equals("") && width == 0
                    && height == 0 && type == 1) {
                Glide.with(context).load(path)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);
            } else if (null != path && !path.trim().equals("") && width > 0
                    && height > 0 && type == 0) {
                Glide.with(context).load(path).override(width, height)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);
            } else if (null != path && !path.trim().equals("") && width > 0
                    && height > 0 && type == 1) {
                Glide.with(context).load(path).override(width, height)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);
            } else if (null != file && width == 0 && height == 0 && type == 0) {
                Glide.with(context).load(file)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);

            } else if (null != file && width == 0 && height == 0 && type == 1) {
                Glide.with(context).load(file)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);
            } else if (null != file && width > 0 && height > 0 && type == 0) {
                Glide.with(context).load(file).override(width, height)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);
            } else if (null != file && width > 0 && height > 0 && type == 1) {
                Glide.with(context).load(file).override(width, height)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);
            } else if (null != path && !path.trim().equals("") && width == 0
                    && height == 0 && type == 2) {
                Glide.with(context).load(path).placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);
            }
        }
    }

    /**
     * 解析出url参数中的键值对 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     *
     * @param url url地址
     * @return url请求参数部分 Action=del&id=123
     */
    @SuppressWarnings("deprecation")
    public static Map<String, String> URLRequest(String url) {

        Map<String, String> mapRequest = new HashMap<String, String>();
        if (!url.equals("") && url.trim().contains("?")) {
            String[] split = url.split("\\?");
            String param_url = split[1];
            if (param_url.contains("&")) {
                String[] param_split = param_url.split("&");
                for (int i = 0; i < param_split.length; i++) {
                    if (param_split[i].contains("=")) {
                        String[] end_split = param_split[i].split("=");
                        mapRequest.put(end_split[0],
                                URLDecoder.decode(end_split[1]));
                    }
                }
            } else {
                if (param_url.contains("=")) {
                    String[] end_two_split = param_url.split("=");
                    mapRequest.put(end_two_split[0],
                            URLDecoder.decode(end_two_split[1]));
                }
            }
        }

        return mapRequest;

    }

    /**
     * 倒计时 控件显示
     *
     * @param times           倒计时时间
     * @param timedown_hour   显示小时控件
     * @param timedown_min    显示分钟控件
     * @param timedown_second 显示秒钟控件
     */
    public static void showTimeDownView(long times, TextView timedown_hour,
                                        TextView timedown_min, TextView timedown_second) {

        try {

            times = times / 1000;
            int mhour = (int) times / 3600;
            int mmin = (int) ((times % 3600) / 60);
            int msecond = (int) times % 60;

            // LogUtils.v("times:"+times+"-mhour:"+mhour+"-mmin:"+mmin +
            // "-msecond:"+msecond);
            if (timedown_hour != null && mhour < 10) {
                timedown_hour.setText("0" + String.valueOf(mhour));
            } else if (timedown_hour != null) {
                timedown_hour.setText(String.valueOf(mhour));
            }
            if (timedown_min != null && mmin < 10) {
                timedown_min.setText("0" + String.valueOf(mmin));
            } else if (timedown_min != null) {
                timedown_min.setText(String.valueOf(mmin));
            }
            if (timedown_second != null && msecond < 10) {
                timedown_second.setText("0" + String.valueOf(msecond));
            } else if (timedown_second != null) {
                timedown_second.setText(String.valueOf(msecond));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重构网页url地址
     *
     * @param url 网页url地址
     * @return 添加参数后的url地址
     */
    public static String constructUrl(String url) {

        try {
            String id = MyApplication.getUserId();
            String user_key = MyApplication.getUserKey();
            String encode_user_key;
            try {
                encode_user_key = URLEncoder.encode(user_key, "utf-8");
            } catch (UnsupportedEncodingException e) {
                encode_user_key = user_key;
            }
            if (url != null) {
                if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(user_key)) {
                    if (url.contains("?")) {
                        if (url.endsWith("?")) {
                            url = url + "id=" + id + "&user_key="
                                    + encode_user_key + "&qt=1"
                                    + "&version=21&shop_id="
                                    + MyApplication.getShopId();
                        } else {
                            url = url + "&id=" + id + "&user_key="
                                    + encode_user_key + "&qt=1"
                                    + "&version=21&shop_id="
                                    + MyApplication.getShopId();
                        }
                    } else {
                        url = url + "?id=" + id + "&user_key="
                                + encode_user_key + "&qt=1"
                                + "&version=21&shop_id="
                                + MyApplication.getShopId();
                    }

                } else {
                    if (!url.contains("?")) {
                        url = url + "?qt=1" + "&version=21&shop_id="
                                + MyApplication.getShopId();
                    } else {
                        url = url + "&qt=1" + "&version=21&shop_id="
                                + MyApplication.getShopId();
                    }
                }
                return url;
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void setBasicUI(Context context) {
        // 透明的状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = ((Activity) context).getWindow();
            // 透明状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {

//			TextView tv_tiltle = (TextView) findViewById(R.id.tv_tiltle);
//			tv_tiltle.setVisibility(View.GONE);
        }
        StatusBarDarkModeUtils.setMeizuStatusBarDarkIcon((Activity) context, true);
        StatusBarDarkModeUtils.setMiuiStatusBarDarkMode((Activity) context, true);
    }

    /**
     * 解析整个Json对象，完成后释放Json对象的内存
     */
    private void initDatas(Context context) {
        String[] mProvinceDatas;
        String[] mProvinceDatasId;
        /**
         * key - 省 value - 市s
         */
        Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
        Map<String, String[]> mCitisDatasIdMap = new HashMap<String, String[]>();
        /**
         * key - 市 values - 区s
         */
        Map<String, String[]> mAreaDatasMap = new HashMap<String, String[]>();
        Map<String, String[]> mAreaDatasIdMap = new HashMap<String, String[]>();
        try {
            JSONArray jsonArray = initJsonData(context).getJSONArray(
                    "locationlist");
            mProvinceDatas = new String[jsonArray.length()];
            mProvinceDatasId = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);// 每个省的json对象
                String province = jsonP.getString("name");// 省名字

                String provinceId = jsonP.getString("id");

                mProvinceDatas[i] = province;

                mProvinceDatasId[i] = provinceId;

                JSONArray jsonCs = null;
                try {
                    jsonCs = jsonP.getJSONArray("city");
                } catch (Exception e1) {
                    continue;
                }
                String[] mCitiesDatas = new String[jsonCs.length()];
                String[] mCitiesDatasId = new String[jsonCs.length()];
                for (int j = 0; j < jsonCs.length(); j++) {
                    JSONObject jsonCity = jsonCs.getJSONObject(j);
                    String city = jsonCity.getString("name");// 市名字

                    String cityId = jsonCity.getString("id");

                    mCitiesDatas[j] = city;

                    mCitiesDatasId[j] = cityId;
                    JSONArray jsonAreas = null;
                    try {
                        /**
                         * Throws JSONException if the mapping doesn't exist or
                         * is not a JSONArray.
                         */
                        jsonAreas = jsonCity.getJSONArray("county");
                    } catch (Exception e) {
                        continue;
                    }

                    String[] mAreasDatas = new String[jsonAreas.length()];// 当前市的所有区
                    String[] mAreasDatasId = new String[jsonAreas.length()];
                    for (int k = 0; k < jsonAreas.length(); k++) {
                        String area = jsonAreas.getJSONObject(k).getString(
                                "name");// 区域的名称

                        String areaId = jsonAreas.getJSONObject(k).getString(
                                "id");

                        mAreasDatas[k] = area;
                        mAreasDatasId[k] = areaId;
                    }
                    mAreaDatasMap.put(city, mAreasDatas);
                    mAreaDatasIdMap.put(cityId, mAreasDatasId);
                }

                mCitisDatasMap.put(province, mCitiesDatas);
                mCitisDatasIdMap.put(provinceId, mCitiesDatasId);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
